<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div{
            border: 1px solid;
            box-sizing: border-box;
        }
        .box{
            width: 300px;
            height: 300px;
        }
        .big{
            width: 300px;
            height: 300px;
            position: absolute;
            left: 400px;
            top: 0;
            background: url('https://aisearch.cdn.bcebos.com/pic_create/2025-11-01/10/17816e89ed3e3c0a.jpg?x-bce-process=image/watermark,image_cGljX2NyZWF0ZS93YXRlcm1hcmsvYWlfd2F0ZXJtYXJrLnBuZw==,x_16,y_16');
            background-size: 600px 600px;
        }
        img{
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="box">
        <img src="https://aisearch.cdn.bcebos.com/pic_create/2025-11-01/10/17816e89ed3e3c0a.jpg?x-bce-process=image/watermark,image_cGljX2NyZWF0ZS93YXRlcm1hcmsvYWlfd2F0ZXJtYXJrLnBuZw==,x_16,y_16" alt="">
    </div>
    <div class="big"></div>
    <script>
        let box=document.querySelector('.box')
        let big= document.querySelector('.big')
        let span =document.querySelector('span')
        //鼠标移动到box上触发移入事件

        // 触发移动事件
        box.onmousemove = function(e){
        console.log(e);
        //计算放大镜遮罩层在x轴上的位置:鼠标x坐标-小图容器左边距-遮罩层宽度的一半，使其居中
        let x = e.pageX-box.style.top-span.offsetwidth / 2
       //计算放大镜遮罩层在y轴上的位置:鼠标y坐标-小图容器顶部距离- 遮罩层高度的一半，使其居中
        let y = e.pageY-box.style.top-span.offsetHeight / 2
        // 限制遮罩层不超出小图容器的左边界
        X<=0?x=0:x
        //限制遮罩层不超出小图容器的上边界
        y<=0?y=0:y
        //计算遮罩层在x轴上可移动的最大距离(小图容器宽度 遮罩层宽度)
        let chawidth =box.offsetWidth -span.offsetwidth
        //计算遮罩层在y轴上可移动的最大距离(小图容器高度 - 遮罩层高度》
        let chaheight = box.offsetHeightspan.offsetHeight
        // 限制遮罩层不超出小图容器的右边界
        x>=chawidth ? x=chawidth :x
        //限制遮罩层不超出小图容器的下边界
        y>=chaheight ? y=chaheight :y
        // 设置遮罩层的水平位置
        span.style.left =x+'px'
        // 设置遮罩层的垂直位置
        span.style.top=y+'px'
        }
    </script>
</body>
</html>